package com.bwc.aidemo.chatting

import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.bwc.aidemo.R
import com.bwc.aidemo.base.BaseActivity
import com.bwc.aidemo.databinding.ActivityChattingBinding
import com.bwc.aidemo.http.AdditionalMessage
import com.bwc.aidemo.http.ApiClient
import com.bwc.aidemo.http.ChatRequest
import com.bwc.aidemo.util.MMKVUtil
import com.google.gson.Gson
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.BufferedReader
import java.io.InputStreamReader

//聊天制定计划
class ChattingActivity : BaseActivity<ActivityChattingBinding>() {

    private lateinit var adapter: ChattingAdapter

    private var shuru : String ?= null
    private var conversationId : String = ""


    override fun getLayoutId(): Int {
        return R.layout.activity_chatting
    }

    override fun initViews() {
        //适配器
        adapter = ChattingAdapter()
        dataBinding.chatRecyc.adapter = adapter
        dataBinding.chatRecyc.layoutManager = LinearLayoutManager(this).apply {
            stackFromEnd = true
        }

        //监听用户输入的值，并且融入至给shuru字段
        dataBinding.chatInput.addTextChangedListener{text ->
            shuru = text.toString()
        }

        Log.d("TAG", "initViews: ${MMKVUtil.get("wenben","kong")}")
        //用户输入事件
        dataBinding.chatSend.setOnClickListener {
            sendMe(shuru)
        }

        adapter.addMessage(Message("你好,我是您的专属ai教练，请告诉我你的身高体重，性别，年龄，身体状况，训练目标，" +
                "以为您制定合适的跑步计划",false))
    }


    private fun sendMe(text: String?){
        if (text == null){
            Toast.makeText(this, "请输入内容后发送", Toast.LENGTH_SHORT).show()
        }else{
            adapter.addMessage(Message(text,true))
            sendMessage(text)
        }
    }


    private fun sendMessage(text : String){


        val additionalMessages = listOf(
            AdditionalMessage(
                content = text,
                content_type = "text",
                role = "user",
                type = "question"
            )
        )

        val chatRequest = ChatRequest(
            bot_id = "7566466192694181938",
            user_id = "123456789",
            stream = true,
            additional_messages = additionalMessages
        )
        adapter.addMessage(Message("",false))


        ApiClient.apiService.sendMessage(conversationId, chatRequest).enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.isSuccessful) {
                    val inputStream = response.body()?.byteStream() ?: return
                    val reader = BufferedReader(InputStreamReader(inputStream))
                    val stringBuilder = StringBuilder()  // 用于拼接完整消息

                    try {
                        var line: String?


                        while (reader.readLine().also { line = it } != null) {
                            if (line.isNullOrBlank()) continue  // 跳过空行

                            val eventType = if (line!!.startsWith("event:")) {
                                line!!.substringAfter("event:").trim()
                            } else {
                                continue  // 非 event 行跳过（如 data: 行后续处理）
                            }

                            // 读取对应的 data 行（下一行通常是 data:xxx）
                            val dataLine = reader.readLine()?.trim() ?: continue
                            if (!dataLine.startsWith("data:")) continue
                            val dataJson = dataLine.substringAfter("data:").trim()

                            // 解析事件并处理
                            when (eventType) {
                                "conversation.message.delta" -> {

                                    val delta = Gson().fromJson(dataJson, MessageData::class.java)
                                    stringBuilder.append(delta.content)
                                    conversationId = delta.conversation_id

                                    // 实时输出（更新UI等）
                                    runOnUiThread {
                                        adapter.updateMessage(adapter.itemCount -1,stringBuilder.toString())
                                    }
                                    println("实时输出: ${stringBuilder.toString()}")
                                }
                                "conversation.message.completed" -> {
                                    // 消息完全结束（可获取完整内容）
                                    val completed = Gson().fromJson(dataJson, MessageData::class.java)
                                    println("完整消息: ${completed.content}")
                                    if (completed.content.contains("+++")){
                                        MMKVUtil.put("wenben",completed.content)
                                    }
                                }
                                "done" -> {
                                    // 整个流式传输结束
                                    println("流式传输完成")
                                    dataBinding.chatInput.text.clear()
                                    break  // 退出循环
                                }
                                // 其他事件可根据需要处理
                                "conversation.chat.created",
                                "conversation.chat.in_progress",
                                "conversation.chat.completed" -> {
                                    // 可记录聊天状态，如"创建中"、"处理中"等
                                }
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        reader.close()
                        inputStream.close()
                    }
                } else {
                    println("请求失败: ${response.code()} ${response.message()}")
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                t.printStackTrace()
            }
        })



    }




    override fun initData() {

    }
}